<?php


namespace app\common\lib;


use GuzzleHttp\Client;
use XznsTools\curl\Curl;

class SensorsDataSearch
{
    private $secret = '194d24499be7cc451f5b2be89d4fb33b6898783cf15fae6c19500d54677d2f09';

    /**
     *  自定义查询
     * @param string $tablename
     * @param string $where
     * @param string $field
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getQuerySearch(string $tablename, string $where = '', string $field = 'distinct_id', int $page = 1, int $limit = 10000)
    {
        $res = Curl::request("https://xingzuonvshen.cloud.sensorsdata.cn/api/sql/query?token={$this->secret}&project=production", [
            'q' => 'select count(*) as `total` from user_group_' . $tablename,
            'format' => 'json'
        ], 'POST', [], 'form_params');

        $pagination = [
            'total' => 0,
            'per_page' => $limit,
            'current_page' => 1,
            'last_page' => 1,
            'data' => []
        ];
        if ($res['success'])
        {
            $pagination['total'] = $res['data']['total'];
            $pagination['last_page'] = (int)ceil($pagination['total'] / $pagination['per_page']);// 总共多少页

            $start = $limit * ($page - 1);
            $sql = 'select ' . $field . ' from user_group_' . $tablename;
            if ($where)
            {
                $sql .= " where {$where} ";
            }
            $sql .= " order by base_time asc limit {$start},{$limit}";

            $resData = $this->request("https://xingzuonvshen.cloud.sensorsdata.cn/api/sql/query?token={$this->secret}&project=production", [
                'q' => $sql,
                'format' => 'json'
            ], 'POST', [], 'form_params');

            $data = array_filter(explode("\n", $resData['data']));

            $data = array_map(function ($value)
            {
                return \GuzzleHttp\json_decode($value, true);
            }, $data);

            $pagination['data'] = array_column($data, $field);
        }

        return $pagination;
    }

    /**
     * 获取分群列表
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getGroupList()
    {
        $res = Curl::request("https://xingzuonvshen.cloud.sensorsdata.cn/api/v2/user_groups", [
            'token' => $this->secret,
            'project' => 'production'
        ], 'GET', []);

        return $res['data'];
    }

    /**
     * 发送请求
     * @param string $url
     * @param array $params
     * @param string $method
     * @param array $configs
     * @param string $contentType
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function request(string $url, array $params = [], string $method = 'POST', array $configs = [], string $contentType = 'form_params'): array
    {

        try
        {
            $client = new Client($configs);
            $params = strtoupper($method) == 'GET' ? $params ? ['query' => $params] : [] : [$contentType => $params];
            $request = $client->request($method, $url, $params);
        }
        catch (\Exception $e)
        {
            $errorCode = $e->getCode();
            $errorMessage = $e->getMessage();

            return [
                'success' => false,
                'errorCode' => $errorCode,
                'errorMessage' => $errorMessage,
            ];
        }

        $httpCode = $request->getStatusCode();
        $return = $request->getBody()->getContents();

        if ($httpCode != 200)
        {
            return [
                'success' => false,
                'errorCode' => $httpCode,
                'errorMessage' => $return,
            ];
        }

        return [
            'success' => true,
            'data' => $return
        ];
    }
}
